#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2009-2010 GSyC/LibreSoft, Universidad Rey Juan Carlos
# 
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see http://www.gnu.org/licenses/.
#
#  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
#			Jose Gato Luis <jgato@libresoft.es>
#
#

from GIC.Channels.Items.NoteItem import *
from GIC.Channels.GenericChannel import *

from urllib2 import urlopen, HTTPError
from xml.dom.minidom import parseString

from Config import channel_icon_url, max_size_search, description
#import sys
#sys.path.insert (0, "../GoogleApi")
#from GoogleApi.GoogleTranslate import *

class Channel11870 (GenericChannel):

	MANDATORY_FIELDS = ["latitude", "longitude", "radius"]
	
	url_api = "http://11870.com/api/v1/search?%s&authSign=3572a8bb3f7dc6c9b2b80907beff2f5f&appToken=74805753bf8cef647b46101266370e05&"
	url_11870 = " "

	def __init__ (self, place):
		self.places_list = []
		self.options = {}
		
	def get_info(self):
		return description
	
	def set_mandatory_fields(self, dict):
	
		for field in self.MANDATORY_FIELDS:
			if not field in dict:
				return (False, field)
			else:
				self.options[field] = dict[field]
		  
		return (True, "")

	def set_config_by_coordenates (self, pattern, latitude, longitude, radius, num_elements):
		
		self.set_search_pattern (pattern)
		self.latitude = latitude
		self.longitude = longitude
		self.radius = radius
		self.num_elements = num_elements

		coordenates = "lat=%s&lon=%s&radius=%s" % (self.latitude, self.longitude, self.radius)
		pattern = "q=%s" % (self.search_pattern) + "&count=" + num_elements

		self.url_11870 = self.url_api % (coordenates) + pattern
	   
	
	def set_options(self, options):
		
		success, result = self.set_mandatory_fields(options)
	
		if not success:
			return False, "\"%s\" parameter is mandatory " % (result)
		
		return True, ""

	def set_config_by_pattern (self, pattern, num_elements):

		self.set_search_pattern(pattern)
		self.num_elements = num_elements

		self.url_11870 = self.url_api % ("q="+pattern) + "&count=" + num_elements + "&as=/es/madrid"


	def process (self):
		url11870 = "http://11870.com/api/v1/search?count=%s&lat=%s&lon=%s&radius=%s&authSign=3572a8bb3f7dc6c9b2b80907beff2f5f&appToken=74805753bf8cef647b46101266370e05&q=%s" %	(max_size_search, self.options["latitude"], self.options["longitude"], self.options["radius"], self.search_pattern )

		try:
			r = urlopen( url11870 )
			string_data = r.read()
			dom = parseString(string_data)
			feed = dom.firstChild
			resp = feed.toxml();
		except HTTPError, e:
			return (False, e )


		for item in feed.getElementsByTagName("entry"):

			place = NoteItem()
			
#			place.service = "11870"
#			place.title = self.getInnerText(item, "title")
#			place.summary = self.getInnerText(item, "summary")
#			place.url = self.getInnerText(item, "id")
#			place.address = self.getInnerText(item, "oos:useraddress")
#			place.phone = self.getInnerText(item, "oos:telephone")
#			place.city = self.getInnerText(item, "oos:locality")
#			place.region = self.getInnerText(item, "oos:subadministrativearea")
#			place.country = self.getInnerText(item, "oos:country")

			place.title = self.getInnerText(item, "title")
			place.text = self.getInnerText(item, "summary")
			place.icon = channel_icon_url
			pos = self.getInnerText(item, "gml:pos")
			
			try:
				latitude = pos.split(' ')[0]
				longitude = pos.split(' ')[1]
								
				place.position = { 'latitude' : latitude,
								  'longitude' : longitude} 
			except ValueError:
				print ValueError
				place.position = { 'latitude' : 0,
								  'longitude' : 0} 


			self.places_list.append (place)

		return (True, self.places_list)
			
	def getInnerText (self, domNode, tag=None):
		try:
			if tag ==None:
				return domNode.childNodes[0].nodeValue
			else:
				return domNode.getElementsByTagName(tag)[0].childNodes[0].nodeValue
		except:
			return None
			
